package com.avic.map.common.util;

import com.avic.map.common.config.CommonProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @Author huangsheng on 2018/11/26
 */
@Slf4j
@Component
public class FileUploadUtil {

    public static final String MAP_CAR_IMAGE_MODULE = "map/car/image/";

    @Autowired
    private CommonProperties commonProperties;

    /**
     * 文件上传处理
     *
     * @param file
     * @return
     */
    public String writeUploadFile(MultipartFile file, String module) {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        log.info("上传的文件名为：" + originalFilename);
        // 获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        if (StringUtils.isBlank(suffixName)) {
            suffixName = ".jpg";
        }
        // 文件上传后的路径
        String filePath = commonProperties.getUploadLocation();
        // 解决中文问题，liunx下中文路径，图片显示问题
        String fileName = module + UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return fileName;
        } catch (Exception e) {
            log.error("上传图片发生错误 {}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }
}
